import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Spin,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
} from 'antd';
import moment from 'moment';
import router from 'umi/router';

import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from './Test.less';

const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default', 'processing', 'success', 'error'];

/* eslint react/no-multi-comp:0 */
@connect(({ rule, loading }) => ({
  rule,
  loading: loading.models.ruleTest,
}))
@Form.create()
class TradingPlanList extends PureComponent {
  state = {
    filterData: [],
    expandForm: false, // 查询菜单栏 是否显示
    listLoading: false,
    formValues: {
      dueDate: '',
      maxEarningsDate: '',
      minBreakEvenMargin: 0,
      minEarningsDate: '',
      minRoyalty: 0,
      minYieldRate: 0,

      orderType: 0, // 排序方向
      orderField: '', // 排序字段
      pageSize: 10, // 页面大小
      pageNum: 1, // 当前页
    }, // 查询菜单栏   查询参数
    modalVisible: false,
    updateModalVisible: false,

    selectedRows: [],

    stepFormValues: {},
  };

  columns = [
    {
      title: '订单类型',
      dataIndex: 'tradeType',
    },
    /*    {
      title: '',
      dataIndex: 'id',
      render: text => <span >{}</span>,
    }, */

    {
      title: '股票代号',
      dataIndex: 'symble',
    },
    {
      title: '市场价格',
      dataIndex: 'marketPrice',
    },
    {
      title: '执行价格',
      dataIndex: 'strikePrice',
    },
    {
      title: '到期日',
      dataIndex: 'expiration',
    },
    {
      title: '到期日天数',
      dataIndex: 'daysToExp',
    },
    {
      title: ' 权利金',
      dataIndex: 'premium',
    },
    {
      title: '最多合约数',
      dataIndex: 'maxContract',
    },
    {
      title: '权利金总额',
      dataIndex: 'totalPremium',
    },
    {
      title: '年回收（扣佣）',
      dataIndex: 'annualizedDeductCommission',
    },
    {
      title: '年回收',
      dataIndex: 'annualized',
    },
    {
      title: '将开的潜在敞口',
      dataIndex: 'potentialExposure',
    },
    {
      title: '折扣',
      dataIndex: 'discount',
    },
    {
      title: '订单有效期',
      dataIndex: 'orderValidityPeriod',
    },
    {
      title: '预计成交幅度',
      dataIndex: 'expectedTradingRange',
    },
  ];

  // 默认加载数据-起始方法
  render() {
    const {
      rule: { data },
      loading,
      total,
    } = this.props;

    const {
      selectedRows,
      modalVisible,
      updateModalVisible,
      stepFormValues,
      listLoading,
    } = this.state;

    return (
      <PageHeaderWrapper title="瑞银sell Put交易计划列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            {/*         <div className={styles.tableListForm}>{this.renderForm()}</div> */}
            <StandardTable
              selectedRows={selectedRows}
              loading={listLoading}
              data={data}
              columns={this.columns}
              onChange={this.handleStandardTableChange}
              rowKey="id"
              pagination={false}
              bordered
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }

  // 加载完 之后 再加载 此 方法
  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'rule/SellPutPlanList',
      payload: formValues,
    });
  }

  // 改变每页条数和当前页
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    formValues.pageNum = pagination.current;
    formValues.pageSize = pagination.pageSize;

    if (sorter.field) {
      // 排序参数
      formValues.orderField = `${sorter.field}`;
      if (sorter.order == 'ascend') {
        formValues.orderType = 2; // 升序
      } else if (sorter.order == 'descend') {
        formValues.orderType = 1; // 降序
      } else {
        formValues.orderType = 0; // 不排序
      }
    } else {
      formValues.orderField = '';
      formValues.orderType = 0; // 不排序
    }
    const params = {
      ...formValues,
      ...filters,
    };
    dispatch({
      type: 'rule/GetRoyaltiesList',
      payload: params,
    });
  };

  // 判断 菜单栏 是 缩放显示 还是 全部展示
  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  // 菜单栏- 点击展开显示 事件
  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="最大财报日">
              {getFieldDecorator('maxEarningsDate ')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入最大财报日" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小财报日">
              {getFieldDecorator('minEarningsDate')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入最小财报日" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小保本幅度">
              {getFieldDecorator('minBreakEvenMargin')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="最小权利金">
              {getFieldDecorator('minRoyalty')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小收益率">
              {getFieldDecorator('minYieldRate')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <div style={{ marginBottom: 24 }}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起 <Icon type="up" />
            </a>
          </div>
        </div>
      </Form>
    );
  }

  // 菜单栏 默认收缩显示 事件
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="最小权利金">
              {getFieldDecorator('minRoyalty')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小收益率">
              {getFieldDecorator('minYieldRate')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <Icon type="down" />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  // 菜单栏-查询按钮 事件
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    const { formValues } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };
      if (values.maxEarningsDate != undefined) {
        formValues.maxEarningsDate = values.maxEarningsDate;
      }
      if (values.minBreakEvenMargin != undefined) {
        formValues.minBreakEvenMargin = parseFloat(values.minBreakEvenMargin);
      }
      if (values.minEarningsDate != undefined) {
        formValues.minEarningsDate = values.minEarningsDate;
      }
      if (values.minRoyalty != undefined) {
        formValues.minRoyalty = parseFloat(values.minRoyalty);
      }
      if (values.minYieldRate != undefined) {
        formValues.minYieldRate = parseFloat(values.minYieldRate);
      }
    });

    dispatch({
      type: 'rule/GetRoyaltiesList',
      payload: formValues,
    });
  };

  // 菜单栏- 重置按钮 事件
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    const { formValues } = this.state;
    form.resetFields();
    formValues.maxEarningsDate = '';
    formValues.minBreakEvenMargin = 0;
    formValues.minEarningsDate = '';
    formValues.minRoyalty = 0;
    formValues.minYieldRate = 0;

    dispatch({
      type: 'rule/GetRoyaltiesList',
      payload: formValues,
    });
  };

  // 菜单栏- 展开 关闭 事件
  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };
}

export default TradingPlanList;
